<template>
  <div id="sidebar-wrap" class="tree-container-left vw20">
    <!--<el-button type="primary" @click="handleCreate()" icon="el-icon-share">添加顶层编码</el-button>-->
    <el-scrollbar class="default-scrollbar" wrap-class="default-scrollbar__wrap">
      <!--<happy-scroll v-if="treedata" color="#cccccc" size="6" class="default-scrollbar__wrap"  resize scroll-top="190" hide-horizontal>-->
        <!--show-checkbox-->
        <el-tree ref="tree"
                 :props="props1"
                 :data="treedata"
                 @node-click="handleNodeClick"
                 node-key="_id"
                 :indent="indent"
                 highlight-current
                 show-checkbox
                 :default-checked-keys="checkedKey"
                 :default-expanded-keys="expandedKey"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>
              <svg-icon v-if="node.data.codeType=='CODE_END'" icon-class="leaf1" />
              <svg-icon v-else icon-class="folder1"/>
              {{ node.label }}</span>
            <span class="nodespan">
              <span>{{ node.data.level }}</span>
              <span>{{ node.data.codeNo }}</span>
              <span>{{ node.data.fullCodeNo }}</span>
            &nbsp;&nbsp;<i class="el-icon-plus" v-if="node.data.codeType=='CODE'" @click.stop="() => append(node)"></i>
              <i v-else>×&nbsp;</i>
            &nbsp;&nbsp;<i class="el-icon-edit" @click.stop="() => edit(node)"></i>
            &nbsp;&nbsp;<i class="el-icon-delete" @click.stop="() => deleteNode(node)"></i>
              <!--<el-button v-if="node.data.codeType=='CODE'" type="text" size="mini" @click.stop="() => append(node)">添加子级</el-button>-->
              <!--<el-button type="text" size="mini" @click.stop="() => edit(node)">修改</el-button>-->
              <!--<el-button type="text" size="mini" @click.stop="() => deleteNode(node)">删除</el-button>-->
            </span>
          </span>
        </el-tree>

        <back-to-top :visibility-height="300" :back-position="50" transition-name="fade"/>

      <!--</happy-scroll>-->
    </el-scrollbar>
  </div>
</template>
<script>
  import {disableBtn, df, $err, $suc, ERRS, SUCS} from '@/utils'
  import {fetchGet, deleteOne} from '@/api/common'
  import BackToTop from '@/components/BackToTop'

  export default {
    name: "treeCode",

    components: {
      BackToTop
    },
    props: {  //子组件接收父组件中的数据,预定义默认值
      /*      selGetData: {
              type: Array,
              default: []
            },
            searchData: {
              type: Object,
              default: {}
            },
            changeSearchData:Array,  //select框选中后的多级数组
            selectId: {
              type: Array,
              default: []
            },
            levStatus: Number*/
    },
    data() {
      return {
        rootData: [],//根节点
        isMusicOn: false,
        isUnique: true,
        isRouter: true,
        treedata: [],
        currentNode: {},//当前操作的data
        selGetData: [],  //多级select 根据level 请求api保存的数组
        indent: 20,
        props1: {
          label: 'explainText',
          children: 'childList',
          isLeaf: 'leaf'
        },
        expandedKey: [],//展开项
        checkedKey: [],//选中项
        choseId:''
      };
    },
    watch: {},

    mounted() {
      this.getList();
    },
    methods: {

      getList() {
        fetchGet(`sparepartscode/codeExplains/all`).then(res => {
          if (res.code === 0) {
            this.treedata = res.data
            if (this.currentNode.data) {
              console.log(this.currentNode);
              this.setKey()
              this.$refs.tree.setCurrentNode(this.currentNode); //通过id选中当前节点
            }
          } else {
            ERRS(res.message)
          }
        })
      },

      append(node) {
        this.setCheckedKey(node.data._id)
        this.currentNode = node
        this.$emit('addcode', node)
        /*        const newChild =  {
                    _id: 27,
                    codeNo: "7771",
                    explainText: "7771",
                    fullCodeNo: "117777771",
                    leaf: true,
                    level: 2,
                    codeType: "CODE",
                    freeze: false,
                    createdTime: "2019-02-27 14:16:40",
                    updatedTime: "2019-02-27 14:16:40"
                  }
                console.log(131231);
                  console.log(node.childList);
                  if (!node.childList) {
                    this.$set(node, 'childList', []);
                  }
                  node.childList.push(newChild);*/
      },
      appendCode(child) {
        if (child.level === 0) {
          this.getList()
        } else {
          const node = this.currentNode.data;
          if (!node.childList) {
            this.$set(node, 'childList', []);
          }
          node.childList.push(child);
        }


      },
      edit(node) {
        this.setCheckedKey(node.data._id)
        this.currentNode = node
        this.$emit('editcode', node)
      },
      removeNode(node) {
        const parent = node.parent;
        const children = parent.childNodes;
        const index = children.findIndex(d => d.id === node.id);
        //叶子三角去除
        if (children.length < 2)
          parent.isLeaf = true
        children.splice(index, 1);
      },
      deleteNode(node) {
        const id = node.data._id
        if (!id)
          ERRS('删除失败,id不存在')
        this.$msgbox({
          // title: '删除',
          message: '确定要删除该类及所有子类吗? 当编码下有关联的备件就无法删除!',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          deleteOne(`sparepartscode/codeExplains`, {id: id}).then(res => {
            console.log('回调remove', res)
            if (res.code === 0) {
              SUCS('删除成功!')
              this.removeNode(node)
            } else {
              ERRS(res.message)
            }
          })
        });
      },
      //getlist 后勾选
      setKey(){
        //设置保存选中保存 getlist刷新加载
        this.expandedKey = [this.choseId]
        this.checkedKey = [this.choseId]
      },
      //选中项展开和选中保存
      setCheckedKey(id) {
        //取消选中保存 getlist刷新加载
        this.expandedKey = []
        this.checkedKey = []
        this.choseId=id
        //展开
        this.$refs.tree.setCheckedKeys([]);
        this.$refs.tree.setChecked(id, true,0); //通过id选中当前勾选状态
        this.$refs.tree.setCurrentKey(id); //通过id选中当前高亮的节点
      },
      //节点点击事件
      handleNodeClick(node) {
        this.setCheckedKey(node._id)
      },

    }
  }
</script>
